<template>
  <div class="p-6">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">通知管理</span>
          <el-button v-if="user.role === 'ADM' || user.role === 'PRE'" type="primary" @click="handleAdd">发布通知</el-button>
        </div>
      </template>

      <el-table :data="tableData" stripe border v-loading="loading">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="contentText" label="内容" show-overflow-tooltip />
        <el-table-column prop="publishTime" label="发布时间">
          <template #default="scope">
            {{ formatTime(scope.row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="handleView(scope.row)" size="small">查看</el-button>
            <el-button 
              v-if="user.role === 'PRE' || user.role === 'ADM'"
              type="danger" 
              @click="handleDelete(scope.row.id)" 
              size="small"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 发布/编辑通知弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '发布通知' : '编辑通知'"
      width="600px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="通知标题" required>
          <el-input v-model="form.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知内容" required>
          <el-input
            v-model="form.contentText"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看通知详情弹窗 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="通知详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="通知标题">{{ currentNotification.title }}</el-descriptions-item>
        <el-descriptions-item label="通知内容">{{ currentNotification.contentText }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatTime(currentNotification.publishTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import axios from 'axios'

// 从 localStorage 获取当前用户
const user = JSON.parse(localStorage.getItem('xm-pro-user'))

// 数据状态
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add')
const currentNotification = ref({})

// 表单数据
const form = ref({
  id: null,
  title: '',
  contentText: '',
  clubId: null,
  activityId: null,
  publishTime: ''
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  try {
    const date = new Date(time)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return time
  }
}

// 获取通知列表
const loadData = async () => {
  loading.value = true
  try {
    // 根据用户角色获取通知
    let res
    if (user.role === 'STU') {
      // 学生获取其所在社团的通知
      const { data: clubData } = await axios.get(`http://localhost:8080/club/selectByStudentId/${user.id}`)
      const clubIds = clubData.data?.map(item => item.id) || []
      if (clubIds.length > 0) {
        res = await request.post('/notification/selectByClubIds', clubIds)
      } else {
        res = { code: '200', data: [] }
      }
    } else {
      // 管理员和社长获取所有通知
      res = await request.get('/notification/selectAll')
    }

    if (res.code === '200') {
      tableData.value = Array.isArray(res.data) ? res.data : []
    } else {
      ElMessage.error(res.msg || '获取通知列表失败')
      tableData.value = []
    }
  } catch (err) {
    console.error('获取通知列表失败:', err)
    ElMessage.error('获取通知列表失败')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 发布通知
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    id: null,
    title: '',
    contentText: '',
    clubId: user.id,
    activityId: 1, // 默认活动ID，可以根据实际需求修改
    publishTime: new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  dialogVisible.value = true
}

// 查看通知
const handleView = (row) => {
  currentNotification.value = row
  viewDialogVisible.value = true
}

// 删除通知
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete(`/notification/deleteById/${id}`)
    if (res.code === '200') {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 保存通知
const handleSave = async () => {
  if (!form.value.title || !form.value.contentText) {
    ElMessage.warning('请填写完整的通知信息')
    return
  }

  try {
    const res = await request.post('/notification/add', form.value)
    if (res.code === '200') {
      ElMessage.success('发布成功')
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(res.msg || '发布失败')
    }
  } catch (err) {
    ElMessage.error('发布失败')
    console.error(err)
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>